package com.iims.project.controller;

import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import com.iims.common.annotation.Log;
import com.iims.common.constant.UserConstants;
import com.iims.common.core.controller.BaseController;
import com.iims.common.core.domain.AjaxResult;
import com.iims.common.core.page.TableDataInfo;
import com.iims.common.enums.BusinessType;
import com.iims.project.domain.CmisProject;
import com.iims.project.service.IProjectService;
import com.iims.project.vo.query.GroupProjectSearchQuery;
import com.iims.project.vo.resp.CmisProjectDetailVo;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

/**
 * @author fanpei
 * @date 2021/7/7 14:17
 */
@Api(tags = "J-项目管理")
@RestController
@RequestMapping("/business/project")
public class ProjectController extends BaseController {

    @Autowired
    private IProjectService projectService;

    /**
     * 获取项目列表
     */
    @ApiOperation(value = "[高级搜索] 分页查询项目列表", response = CmisProjectDetailVo.class)
    @ApiOperationSupport(order = 1)
    @ApiImplicitParams({
            @ApiImplicitParam(value = "当前记录起始索引(从1开始)", name = "pageNum", paramType = "query", required = true),
            @ApiImplicitParam(value = "每页显示记录数（>0）", name = "pageSize", paramType = "query", required = true),
            @ApiImplicitParam(value = "排序列", name = "orderByColumn", paramType = "query"),
            @ApiImplicitParam(value = "升降序方式：0升序 1降序", name = "isAsc", paramType = "query"),
            @ApiImplicitParam(value = "创建开始时间:format = \"yyyy-MM-dd\"", name = "beginTime", paramType = "query"),
            @ApiImplicitParam(value = "创建结束时间:format = \"yyyy-MM-dd\"", name = "endTime", paramType = "query"),
            @ApiImplicitParam(value = "项目状态,值来源于字典business_project_status", name = "proStatus", paramType = "query"),
            @ApiImplicitParam(value = "项目属性,值来源于字典business_project_proAttr", name = "proAttr", paramType = "query"),
            @ApiImplicitParam(value = "项目名称:模糊匹配", name = "proName", paramType = "query"),
            @ApiImplicitParam(value = "项目编号:模糊匹配", name = "proCode", paramType = "query"),
            @ApiImplicitParam(value = "负责人:模糊匹配", name = "userChargeCN", paramType = "query")
    })
    @PreAuthorize("@ss.hasPermi('business:project:list')")
    @GetMapping("/list")
    public TableDataInfo list(@ApiIgnore CmisProject project) throws Exception {
        startPage();
        setSearchTimeRange(project);
        setSeqNumPageSizeStart(project);
        return getDataTable(projectService.getProjectList(project));
    }

    /**
     * 获取项目列表
     */
    @ApiOperation(value = "[分组搜索] 分页查询项目列表", notes = "按钮分组顺序：scopeValue、proAttr、proType、proStatus、timeValue", response = CmisProjectDetailVo.class)
    @ApiOperationSupport(order = 2)
    @ApiImplicitParams({
            @ApiImplicitParam(value = "当前记录起始索引(从1开始)", name = "pageNum", paramType = "query", required = true),
            @ApiImplicitParam(value = "每页显示记录数（>0）", name = "pageSize", paramType = "query", required = true),
            @ApiImplicitParam(value = "排序列", name = "orderByColumn", paramType = "query"),
            @ApiImplicitParam(value = "升降序方式：0升序 1降序", name = "isAsc", paramType = "query"),
            @ApiImplicitParam(value = "综合模糊搜索:项目名称/项目编号/ERP编号/项目负责人/合同名称/合同编号", name = "searchValue", paramType = "query")
    })
    @PreAuthorize("@ss.hasPermi('business:project:list')")
    @GetMapping("/groupList")
    public TableDataInfo groupList(GroupProjectSearchQuery groupSearchQuery) throws Exception {
        startPage();
        setSeqNumPageSizeStart(groupSearchQuery);
        return getDataTable(projectService.getProjectListByGroup(groupSearchQuery));
    }

    @ApiOperation(value = "获取 [合同] 所属项目列表", response = CmisProjectDetailVo.class)
    @GetMapping("/listByContract/{contractId}")
    public AjaxResult listByContract(@ApiParam(value = "正式合同Id", required = true) @PathVariable Long contractId) {
        return AjaxResult.success(projectService.getContractProjectList(contractId));
    }

    /**
     * 根据项目编号获取详细信息
     */
    @ApiOperation(value = "根据项目Id获取详细信息", response = CmisProjectDetailVo.class)
    @ApiImplicitParam(name = "projectId", value = "项目Id", paramType = "path", required = true)
    @PreAuthorize("@ss.hasPermi('business:project:query')")
    @GetMapping(value = "/{projectId}")
    public AjaxResult getInfo(@PathVariable Long projectId) {
        return AjaxResult.success(projectService.getProjectDetailById(projectId));
    }

    /**
     * 新增项目
     */
    @ApiOperation(value = "新增项目")
    @ApiOperationSupport(ignoreParameters = {"proId", "proCode", "proStatus", "userChargeCN", "deptChargeCN"})
    @PreAuthorize("@ss.hasPermi('business:project:add')")
    @Log(title = "新增项目", businessType = BusinessType.INSERT)
    @Transactional
    @PostMapping
    public AjaxResult add(@Validated @RequestBody CmisProject project) {
        if (UserConstants.NOT_UNIQUE.equals(projectService.checkProNameUnique(project))) {
            return AjaxResult.error("新增项目'" + project.getProName() + "'失败，项目名称已存在");
        }
        projectService.insertProject(project);
        return AjaxResult.success();
    }

    /**
     * 修改项目
     */
    @ApiOperation("修改项目")
    @PreAuthorize("@ss.hasPermi('business:project:edit')")
    @ApiOperationSupport(ignoreParameters = {"proCode", "proStatus", "userChargeCN", "deptChargeCN"})
    @Log(title = "修改项目", businessType = BusinessType.UPDATE)
    @Transactional
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody CmisProject project) {
        if (UserConstants.NOT_UNIQUE.equals(projectService.checkProNameUnique(project))) {
            return AjaxResult.error("修改项目'" + project.getProName() + "'失败，项目名称已存在");
        }
        projectService.updateProject(project);
        return AjaxResult.success();
    }

    /**
     * 删除项目
     */
    @ApiOperation("删除项目")
    @PreAuthorize("@ss.hasPermi('business:project:remove')")
    @Log(title = "删除项目", businessType = BusinessType.DELETE)
    @Transactional
    @DeleteMapping("/{projectId}")
    public AjaxResult remove(@ApiParam("项目Id") @PathVariable Long projectId) {
        if (projectService.checkCmisProjectUse(projectId)) {
            return AjaxResult.error("删除项目失败，项目已被使用！");
        }
        projectService.deleteById(projectId);
        return AjaxResult.success();
    }
}
